package cn.neusoft.yp.controller;

import cn.neusoft.yp.pojo.Product;
import cn.neusoft.yp.service.ProdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gaosheng on 2017/4/27.
 */
@Controller
public class CartController {

    @Autowired
    private ProdService prodService;

    @RequestMapping("cart")
    public String cart(){
        return "cart" ;
    }

    @RequestMapping("addCart")
    public String addCart(String id, HttpSession session) {
        Product prod = prodService.findOne(id);
        Object objCart = session.getAttribute("cart");
        Map<Product, Integer> cart = null;
        if (objCart != null) {
            cart = (Map<Product, Integer>) objCart;
        } else {
            cart = new HashMap<Product, Integer>();
            session.setAttribute("cart", cart);
        }
        if (cart.containsKey(prod)) {
            cart.put(prod, cart.get(prod) + 1);
        } else {
            cart.put(prod, 1);
        }
        return "cart";
    }
    @RequestMapping("deleteCart")
    public String deleteCart(String id, HttpSession session) {

        Product prod = new Product();
        prod.setId(id);
        Object obj = session.getAttribute("cart");
        if (obj != null) {
            Map<Product, Integer> cart = (Map<Product, Integer>) obj;
            cart.remove(prod);
        }
        return "cart";
    }

    @RequestMapping("updateCart")
    public String updateCart(String id, int newBuyNum, HttpSession session) {
        Map<Product, Integer> cart = (Map<Product, Integer>) session.getAttribute("cart");
        //准备key
        Product prod = new Product();
        prod.setId(id);
        cart.put(prod, newBuyNum);

        return  "cart" ;
    }
}